import db from '../utils/db';
import supabaseService from './supabaseService';

const quizHistoryService = {
    async syncHistory() {
        let allHistory = await db.getAll('quizHistory');
        allHistory = allHistory.map(h => {return { "content" : h}})
        await supabaseService.signUpOrIn();
        const { data, error } = await supabaseService.getSupabase()
            .from('quiz_history')
            .upsert(allHistory)     
            .select();
        if (error) {
            console.error('Error syncing history:', error);
            return;
        }
        console.log('Synced history:', data);
    },
    async getHistory(chapterTitle: string, quizTitle?: string): Promise<any[]> {
        let query = supabaseService.getSupabase().from('quiz_history').select('*');
        if (chapterTitle) {
            query = query.eq('content->>chapterTitle', chapterTitle);
        }
        if (quizTitle) {
            query = query.eq('content->>quizTitle', quizTitle);
        }
        const { data, error } = await query;
        if (error) {
            console.error('Error fetching history:', error);
            return [];
        }
        return data || [];
    },
    async updateHistory(currentQuiz: any, selectedIndex: number) {
        const now = Date.now();
        const { book_title, chapter_title } = currentQuiz.basic_info;
        const quizTitle = currentQuiz.question;
        const correct = selectedIndex === currentQuiz.correctAnswerIndex;
        const existingArr = await quizHistoryService.getHistory(chapter_title, quizTitle);
        const quizId = existingArr.length > 0 ? existingArr[0].id : null;
        const existing = existingArr.length > 0 ? existingArr[0].content : null;
      
        const newHistory = existing?.history || [];
        newHistory.push({ selectedIndex, correct, timestamp: now });
      
        const correctStreak = correct
          ? (existing?.correctStreak ?? 0) + 1
          : 0;
      
        const proficiency = Math.min(
          100,
          Math.max(10, (existing?.proficiency ?? 50) + (correct ? 10 : -15))
        );
      
        const nextReviewAt = now + getIntervalMs(correctStreak);
        const historyObj = {
            quizTitle,
            chapterTitle: chapter_title,
            bookTitle: book_title,
            history: newHistory,
            correctStreak,
            proficiency,
            lastReviewed: now,
            nextReviewAt,
          };
        let payload = {
            id: quizId,
            content: historyObj
        };
        if(!quizId){
            delete payload['id'];
        }
        await supabaseService.getSupabase().from('quiz_history')
        .upsert(payload);
    }
}


function getIntervalMs(streak: number): number {
    const days = [1, 2, 4, 7, 15, 30];
    const interval = days[Math.min(streak, days.length - 1)];
    return interval * 24 * 60 * 60 * 1000;
  }

export default quizHistoryService;